package db

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"hr/api/dto"
)

type Dict struct {
	AppModel
	Name     string `gorm:"size:64" json:"name"`
	CreateBy string `gorm:"size:128" json:"createBy"` // 创建人
	UpdateBy string `gorm:"size:128" json:"updateBy"` // 更新人
	Remark   string `gorm:"size:255" json:"remark"`   //备注

	DictValue []DictValue `json:"dict_value"`
}

func (m *Dict) TableName() string {
	return "dict"
}

type DictPageModel struct {
	Total    int64  `json:"total"`
	Result   []Dict `json:"result"`
	PageNo   int    `json:"pageNo"`
	PageSize int    `json:"pageSize"`
}

// GetDict 根据条件查找
func GetDict(p map[string]interface{}, extra ...interface{}) (Dict, error, string) {
	f := Dict{}
	queryDb := GetInstance().Where(p).First(&f)
	if len(extra) > 0 {
		queryDb = queryDb.Where(extra)
	}
	err := queryDb.Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return f, errors.New("查无记录"), "0"
		}
		return f, errors.New(err.Error()), "1"
	}
	return f, nil, "2"
}

func GetDictPaging(pagination dto.Pagination, name string) (DictPageModel, error) {
	result := DictPageModel{
		Total:    0,
		Result:   make([]Dict, 0),
		PageNo:   pagination.PageNo,
		PageSize: pagination.PageSize,
	}
	offset := (pagination.PageNo - 1) * pagination.PageSize
	dbs := GetInstance().Preload("DictValue").Model(&Dict{})
	if name != "" {
		dbs = dbs.Where("dict.name LIKE ?", "%"+name+"%")
	}

	if err := dbs.Offset(offset).Limit(pagination.PageSize).Find(&result.Result).Error; err != nil {
		return result, err
	}
	if err := dbs.Offset(-1).Limit(-1).Count(&result.Total).Error; err != nil {
		return result, err
	}
	return result, nil
}

func GetDictByKey(key string) (Dict, error) {
	dict := Dict{}
	dbs := GetInstance().Preload("DictValue").Where("name = ?", key).Model(&Dict{})
	if err := dbs.First(&dict).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return dict, errors.New("查无记录")
		}
		return dict, err
	}
	return dict, nil
}

func CreateDict(p dto.CommonRequest, user string) (Dict, error) {
	d := Dict{
		Name:      p.Name,
		CreateBy:  user,
		Remark:    p.Remark,
	}
	if err := GetInstance().Create(&d).Error;err !=nil {
		return d,errors.New("创建失败")
	}
	return d,nil
}

func UpdateDict(id uint,p dto.CommonRequest, userId string) (Dict,error) {
	f := Dict{
		AppModel: AppModel{
			ID:        id,
		},
	}
	err := GetInstance().Model(&f).Updates(Dict{
		Name: p.Name,
		Remark: p.Remark,
		UpdateBy: userId,
	}).Scan(&f).Error
	if err != nil {
		return f,err
	}
	return f,nil
}

func DeleteDict(id uint) (Dict,error) {
	f := Dict{}
	err := GetInstance().Exec(fmt.Sprintf("DELETE FROM dict_value WHERE dict_id = %d", id)).Error
	err = GetInstance().Unscoped().Where("id = ?", id).Delete(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}